package com.example.aicooking.controller;

import com.example.aicooking.entity.dto.UserFollowDTO;
import com.example.aicooking.service.UserRelationService;
import com.example.aicooking.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/relations")
@Slf4j
public class UserRelationController {
    @Autowired
    private UserRelationService relationService;

    /**
     * 粉丝查询
     * @param userId
     * @return
     */
    @GetMapping("/followers/{userId}")
    public Result<List<UserFollowDTO>> getFollowers(@PathVariable Long userId) {
        try {
            List<UserFollowDTO> followers = relationService.getFollowers(userId);
            return Result.success(followers);
        } catch (Exception e) {
            log.error("获取粉丝列表失败", e);
            return Result.error("获取粉丝列表失败");
        }
    }
    /**
     * 关注查询
     * @param userId
     * @return
     */
    @GetMapping("/following/{userId}")
    public Result<List<UserFollowDTO>> getFollowing(@PathVariable Long userId) {
        try {
            // 添加请求日志
            log.info("收到关注查询请求: userId={}", userId);
            List<UserFollowDTO> following = relationService.getFollowing(userId);
            return Result.success(following);
        } catch (Exception e) {
            log.error("获取关注列表失败", e);
            return Result.error("获取关注列表失败");
        }
    }

    @PostMapping("/toggle/{targetId}")
    public Result<Map<String, Object>> toggleFollow(@PathVariable Long targetId,
                                                    @RequestHeader("userId") Long userId) {
        try {
            boolean isFollowing = relationService.toggleFollow(userId, targetId);
            Map<String, Object> result = new HashMap<>();
            result.put("following", isFollowing);
            result.put("message", isFollowing ? "关注成功" : "已取消关注");
            return Result.success(result);
        } catch (Exception e) {
            log.error("切换关注状态失败", e);
            return Result.error("操作失败");
        }
    }

    /**
     *检查关注状态
     * @param targetId
     * @param userId
     * @return
     */
    @GetMapping("/check/{targetId}")
    public Result<Boolean> checkFollowStatus(@PathVariable Long targetId,
                                             @RequestHeader("userId") Long userId) {
        // 添加请求日志
        log.info("收到关注状态检查请求: targetId={}, userId={}", targetId, userId);

        try {
            boolean isFollowing = relationService.isFollowing(userId, targetId);
            log.info("关注状态检查结果: {}", isFollowing);
            return Result.success(isFollowing);
        } catch (Exception e) {
            log.error("检查关注状态失败", e);
            return Result.error("检查关注状态失败");
        }
    }
}
